package com.youth.commonutils;

import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author：CM
 * @Package：com.youth.commonutils
 * @Project：youth-college
 * @name：BeanCopyUtils
 * @Date：2023/4/27 11:32
 * @Filename：BeanCopyUtils
 */

public class BeanCopyUtils {

    public static <T, R> List<T> copyBeanToList(List<R> resource, Class targetClass) {
        List<T> target = new ArrayList<>();
        for (R r : resource) {
            T t = copyBean(r, targetClass);
            target.add(t);
        }
        return target;
    }


    public static <T, R> T copyBean(R resource, Class targetClass) {
        T target = null;
        try {
            target = (T) targetClass.newInstance();
            BeanUtils.copyProperties(resource, target);

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return target;
    }
}
